<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body {margin: 0;overflow: hidden;}
    #canvas {background-color: antiquewhite;}
  </style>
</head>
<body>
  <canvas id="canvas"></canvas>
  <script>
    /** @type {HTMLCanvasElement} */
    const canvas = document.querySelector('#canvas');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    const ctx = canvas.getContext('2d');

    const img = new Image();
    img.src = './images/river.jpg';
    img.onload = draw;

    /* 灰度算法: 0.299 * r + 0.587 * g + 0.114 * b; */

    function draw () {
      // 图像尺寸
      const { width, height } = img;

      /* 1.在canvas中绘制图形 */
      ctx.drawImage(img, 0, 0);

      /* 2.从canvas中获取图像的ImageData */
      const imgDt = ctx.getImageData(0,0,width,height);
      const data = imgDt.data;

      // 像素遍历
      for (let i = 0; i < data.length; i+=4) {
        let [r,g,b,a] = [
          data[i],
          data[i+1],
          data[i+2],
          data[i+3],
        ]
        const lm = 0.299 * r + 0.587 * g + 0.114 * b;
        data[i] = lm;
        data[i+1] = lm;
        data[i+2] = lm;
      }

      /* 在canvas中显示ImageData */
      ctx.putImageData(imgDt,0,height);
    }

  </script>
</body>
</html>